package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.comparator.MyComparatorBigToSmall;
import com.itheima.dao.BlogDao;
import com.itheima.dao.BlogTagDao;
import com.itheima.entity.Page;
import com.itheima.pojo.Blog;
import com.itheima.pojo.Tag;
import com.itheima.service.BlogTagService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.IdWorker;
import com.itheima.utils.StringUtils;
import com.itheima.vo.TagVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class BlogTagServiceImpl implements BlogTagService {
    @Autowired
    IdWorker idWorker;

    @Autowired
    private BlogDao blogDao;


    @Autowired
    private BlogTagDao blogTagDao;

    @Override
    public void add(TagVO tagVO) {
//因为置顶权重为101,所有在添加和修改的时候权重不能大于100[前台做校验]
        if (tagVO.getSort()>100){
            throw new RuntimeException("权重设置的时候不可以大于100");
        }

        Tag tag = new Tag();
        tag.setUid(String.valueOf(idWorker.nextId()));
        tag.setContent(tagVO.getContent());
        tag.setStatus(1);
        tag.setCreateTime(DateUtils.getNowTime());
        tag.setUpdateTime(DateUtils.getNowTime());
        tag.setSort(tagVO.getSort());
        tag.setClickCount(0);

        blogTagDao.insertSelective(tag);
    }

    @Override
    public void deleteBatch(TagVO tagVO) {
        String uids = tagVO.getUid();
        String[] split = uids.split(",");
        if (split!=null&&split.length>0){
            for (String s : split) {
                Tag tag = new Tag();
                tag.setUid(s);
                tag.setUpdateTime(DateUtils.getNowTime());
                tag.setStatus(0);
                blogTagDao.updateByPrimaryKeySelective(tag);
            }
        }

    }

    @Override
    public void edit(TagVO tagVO) {
        //因为置顶权重为101,所有在添加和修改的时候权重不能大于100[前台做校验]
        if (tagVO.getSort()>100){
            throw new RuntimeException("权重设置的时候不可以大于100");
        }

        //获取前台传来的uid
        Tag tag = new Tag();
        tag.setUid(tagVO.getUid());
        tag.setContent(tagVO.getContent());
        tag.setSort(tagVO.getSort());
        tag.setUpdateTime(DateUtils.getNowTime());

        blogTagDao.updateByPrimaryKeySelective(tag);
    }

    @Override
    public List<Tag> stick(TagVO tagVO) {
        Tag tag = new Tag();
        //将权重设置为最大
        tag.setSort(101);
        tag.setUid(tagVO.getUid());
        tag.setUpdateTime(DateUtils.getNowTime());
        blogTagDao.updateByPrimaryKeySelective(tag);
        //调用查询所有方法
        return this.getList(tagVO);
    }

    @Override
    public List<Tag> tagSortByCite() {
        PageHelper.startPage(1, 10);
        List<Map<String, Object>> blogCountByTag = blogTagDao.selectSortByCite();

        Map<String, Integer> tagMap = new HashMap<>();

        for (Map<String, Object> map : blogCountByTag) {
            String tagUid = String.valueOf(map.get("tag_uid"));
            //Number是Integer,Long的父类
            Number number = (Number) map.get("referCount");
            Integer count = number.intValue();

            //判断是否只有一个uid
            if (tagUid.length() <= 32) {
                //判断有没有内容
                if (tagMap.get(tagUid) == null) {
                    tagMap.put(tagUid, count);
                } else {
                    Integer tempCount = tagMap.get(tagUid) + count;
                    tagMap.put(tagUid, tempCount);
                }
            } else {
                //包含“，”说明有多个uid
                if (StringUtils.isNotEmpty(tagUid)) {
                    List<String> strList = StringUtils.changeStringToString(tagUid, ",");
                    for (String strItem : strList) {
                        if (tagMap.get(strItem) == null) {
                            tagMap.put(strItem, count);
                        } else {
                            Integer tempCount = tagMap.get(strItem) + count;
                            tagMap.put(strItem, tempCount);
                        }
                    }
                }
            }
        }
        //将tagMap中的值倒序排序
        TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(new MyComparatorBigToSmall());
        if (tagMap != null && tagMap.size() > 0) {
            Set<Map.Entry<String, Integer>> entries = tagMap.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                treeMap.put(entry.getValue(), entry.getKey());
            }
        }
        //将treeMap中的值取出 得到的是倒序排序后的uid集合 根据uid查询出每一个blogsort 放到list集合中
        ArrayList<Tag> blogSorts = new ArrayList<>();
        Collection<String> blosSortUids = treeMap.values();
        if (blosSortUids != null && blosSortUids.size() > 0) {
            for (String uid : blosSortUids) {
                Tag tag = blogTagDao.selectByPrimaryKey(uid);
                blogSorts.add(tag);
            }
        }
        return blogSorts;
    }

    @Override
    public List<Tag> tagSortByClickCount() {
        PageHelper.startPage(1,10);
        return blogTagDao.selectSortByClickCount();
    }

    @Override
    public List<Blog> getArticleByTagUid(String tagUid,Integer currentPage,Integer pageSize) {
        if(currentPage==null||currentPage==0){
            currentPage=1;
        }
        if(pageSize==null||pageSize==0){
            pageSize=10;
        }
        PageHelper.startPage(currentPage.intValue(),pageSize.intValue());
        List<Blog> blogList = blogDao.selectByTagUid(tagUid);
        return blogList;
    }

    @Override
    public List<Tag> getTagList() {
        Example example=new Example(Tag.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("status",1);
        return blogTagDao.selectByExample(example);

    }
    //获取博客分类列表
    @Override
    public List<Tag> getList(TagVO tagVO) {
        //获取分页信息
        Integer page = tagVO.getCurrentPage();
        if (page==null||page==0){
            page=0;
        }
        Integer size = tagVO.getPageSize();
        if (page==null||page==0){
            size=10;
        }
        PageHelper.startPage(page,size);

        Example example = createExample(tagVO);
        return (List<Tag>) blogTagDao.selectByExample(example);
    }

    @Override
    public Tag getTagByUid(String tagUid) {
        Tag tag = blogTagDao.selectByPrimaryKey(tagUid);
        return tag;
    }

    @Override
    public List<Blog> getHotTag() {
        List<Blog> blogList = blogDao.getHotTag();
        return blogList;
    }

    /**
     * 构建查询对象
     * @param tagVO
     * @return
     */
    private Example createExample(TagVO tagVO) {
        Example example = new Example(Tag.class);
        Example.Criteria criteria = example.createCriteria();
        if (tagVO != null) {
            // 关键字
            if (tagVO.getKeyword()!= null && !"".equals(tagVO.getKeyword())) {
                criteria.andLike("content", "%" + tagVO.getKeyword() + "%");
            }
            //状态为1的才显示
            criteria.andEqualTo("status",1);
            //按权重排序
            example.setOrderByClause("SORT DESC");
        }
        return example;
    }
}
